/// 格式化文件大小为人类可读的格式
pub fn format_file_size(size: u64) -> String {
    const UNITS: &[&str] = &["B", "KB", "MB", "GB", "TB"];
    let mut size = size as f64;
    let mut unit_index = 0;
    
    while size >= 1024.0 && unit_index < UNITS.len() - 1 {
        size /= 1024.0;
        unit_index += 1;
    }
    
    if unit_index == 0 {
        format!("{} {}", size as u64, UNITS[unit_index])
    } else {
        format!("{:.1} {}", size, UNITS[unit_index])
    }
}

/// 验证仓库名称是否符合规范
pub fn validate_repo_name(name: &str) -> bool {
    if name.is_empty() || name.len() > 100 {
        return false;
    }
    
    // 只允许字母、数字、连字符和下划线
    name.chars().all(|c| c.is_alphanumeric() || c == '-' || c == '_')
}

/// 检查是否为有效的仓库ID格式 (username/repo-name)
pub fn is_valid_repo_id(repo_id: &str) -> bool {
    let parts: Vec<&str> = repo_id.split('/').collect();
    if parts.len() != 2 {
        return false;
    }
    
    !parts[0].is_empty() && !parts[1].is_empty() && validate_repo_name(parts[1])
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_format_file_size() {
        assert_eq!(format_file_size(512), "512 B");
        assert_eq!(format_file_size(1024), "1.0 KB");
        assert_eq!(format_file_size(1048576), "1.0 MB");
        assert_eq!(format_file_size(1073741824), "1.0 GB");
    }

    #[test]
    fn test_validate_repo_name() {
        assert!(validate_repo_name("my-repo"));
        assert!(validate_repo_name("my_repo"));
        assert!(validate_repo_name("repo123"));
        assert!(!validate_repo_name(""));
        assert!(!validate_repo_name("repo name")); // 包含空格
        assert!(!validate_repo_name(&"a".repeat(101))); // 太长
    }

    #[test]
    fn test_is_valid_repo_id() {
        assert!(is_valid_repo_id("user/my-repo"));
        assert!(is_valid_repo_id("org/project_name"));
        assert!(!is_valid_repo_id("invalid")); // 缺少斜杠
        assert!(!is_valid_repo_id("/repo")); // 缺少用户名
        assert!(!is_valid_repo_id("user/")); // 缺少仓库名
        assert!(!is_valid_repo_id("user/invalid repo")); // 仓库名包含空格
    }
}